"""
报告相关模型
"""
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, ForeignKey, JSON, Float
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from enum import Enum
from typing import Optional, Dict, Any

from .base import Base, TimestampMixin, ActiveMixin


class ReportStatus(str, Enum):
    """报告状态枚举"""
    PENDING = "pending"
    GENERATING = "generating"
    COMPLETED = "completed"
    FAILED = "failed"
    PUBLISHED = "published"
    ARCHIVED = "archived"


class ReportFormat(str, Enum):
    """报告格式枚举"""
    PDF = "pdf"
    WORD = "word"
    EXCEL = "excel"
    HTML = "html"


class ReportType(str, Enum):
    """报告类型枚举"""
    SUMMARY = "summary"
    DETAILED = "detailed"
    STATISTICAL = "statistical"
    CUSTOM = "custom"


class Report(Base, TimestampMixin, ActiveMixin):
    """报告模型"""
    
    __tablename__ = "report"
    
    # 基本信息
    title = Column(String(500), nullable=False, comment="报告标题")
    description = Column(Text, comment="报告描述")
    report_type = Column(String(50), nullable=False, comment="报告类型")
    format = Column(String(20), nullable=False, comment="报告格式")
    status = Column(String(20), default=ReportStatus.PENDING, comment="报告状态")
    
    # 时间范围
    start_date = Column(DateTime, comment="开始日期")
    end_date = Column(DateTime, comment="结束日期")
    
    # 数据范围
    data_source_ids = Column(JSON, comment="数据源ID列表")
    task_ids = Column(JSON, comment="任务ID列表")
    region_filter = Column(JSON, comment="区域过滤器")
    pollution_type_filter = Column(JSON, comment="污染类型过滤器")
    
    # 报告配置
    template_id = Column(Integer, ForeignKey('report_template.id'), comment="模板ID")
    config = Column(JSON, comment="报告配置")
    ai_prompt = Column(Text, comment="AI提示词")
    
    # 文件信息
    file_path = Column(String(500), comment="文件路径")
    file_name = Column(String(255), comment="文件名")
    file_size = Column(Integer, comment="文件大小")
    
    # 生成信息
    generation_time = Column(Float, comment="生成时长(秒)")
    page_count = Column(Integer, comment="页数")
    chart_count = Column(Integer, default=0, comment="图表数量")
    
    # 发布信息
    published_at = Column(DateTime, comment="发布时间")
    published_by = Column(Integer, ForeignKey('user.id'), comment="发布人ID")
    
    # 创建者
    creator_id = Column(Integer, ForeignKey('user.id'), comment="创建者ID")
    
    # 错误信息
    error_message = Column(Text, comment="错误信息")
    error_details = Column(JSON, comment="错误详情")
    
    # 关系
    # template = relationship("ReportTemplate", back_populates="reports")
    # creator = relationship("User", back_populates="created_reports", foreign_keys=[creator_id])
    # publisher = relationship("User", foreign_keys=[published_by])
    
    def start_generation(self):
        """开始生成报告"""
        self.status = ReportStatus.GENERATING
    
    def complete_generation(self, file_path: str, file_name: str, generation_time: float = None):
        """完成报告生成"""
        self.status = ReportStatus.COMPLETED
        self.file_path = file_path
        self.file_name = file_name
        if generation_time is not None:
            self.generation_time = generation_time
        
        # 获取文件大小
        import os
        if os.path.exists(file_path):
            self.file_size = os.path.getsize(file_path)
    
    def fail_generation(self, error_message: str = None, error_details: Dict = None):
        """报告生成失败"""
        self.status = ReportStatus.FAILED
        self.error_message = error_message
        self.error_details = error_details
    
    def publish(self, published_by: int):
        """发布报告"""
        self.status = ReportStatus.PUBLISHED
        self.published_at = func.now()
        self.published_by = published_by
    
    def archive(self):
        """归档报告"""
        self.status = ReportStatus.ARCHIVED
    
    def get_file_info(self) -> Dict[str, Any]:
        """获取文件信息"""
        import os
        if self.file_path and os.path.exists(self.file_path):
            stat = os.stat(self.file_path)
            return {
                "exists": True,
                "size": stat.st_size,
                "modified_time": stat.st_mtime,
                "created_time": stat.st_ctime
            }
        return {"exists": False}
    
    def to_dict(self) -> dict:
        """转换为字典"""
        result = super().to_dict()
        result['file_info'] = self.get_file_info()
        return result


class ReportTemplate(Base, TimestampMixin, ActiveMixin):
    """报告模板模型"""
    
    __tablename__ = "report_template"
    
    # 基本信息
    name = Column(String(200), nullable=False, comment="模板名称")
    description = Column(Text, comment="模板描述")
    report_type = Column(String(50), nullable=False, comment="报告类型")
    format = Column(String(20), nullable=False, comment="报告格式")
    category = Column(String(50), comment="模板分类")
    
    # 模板内容
    template_content = Column(Text, comment="模板内容")
    template_config = Column(JSON, comment="模板配置")
    field_mapping = Column(JSON, comment="字段映射")
    
    # AI配置
    ai_prompt_template = Column(Text, comment="AI提示词模板")
    ai_model_config = Column(JSON, comment="AI模型配置")
    
    # 样式配置
    style_config = Column(JSON, comment="样式配置")
    chart_config = Column(JSON, comment="图表配置")
    
    # 使用统计
    usage_count = Column(Integer, default=0, comment="使用次数")
    last_used = Column(DateTime, comment="最后使用时间")
    
    # 创建者
    creator_id = Column(Integer, ForeignKey('user.id'), comment="创建者ID")
    
    # 是否系统模板
    is_system = Column(Boolean, default=False, comment="是否系统模板")
    
    # 排序
    sort_order = Column(Integer, default=0, comment="排序顺序")
    
    # 关系
    # creator = relationship("User")
    # reports = relationship("Report", back_populates="template")
    
    def increment_usage(self):
        """增加使用次数"""
        self.usage_count += 1
        self.last_used = func.now()
    
    def to_dict(self) -> dict:
        """转换为字典"""
        result = super().to_dict()
        return result


class ReportSchedule(Base, TimestampMixin, ActiveMixin):
    """报告定时任务模型"""
    
    __tablename__ = "report_schedule"
    
    # 基本信息
    name = Column(String(200), nullable=False, comment="任务名称")
    description = Column(Text, comment="任务描述")
    
    # 调度配置
    schedule_type = Column(String(50), comment="调度类型")
    schedule_config = Column(JSON, comment="调度配置")
    next_run_time = Column(DateTime, comment="下次运行时间")
    last_run_time = Column(DateTime, comment="最后运行时间")
    
    # 报告配置
    template_id = Column(Integer, ForeignKey('report_template.id'), comment="模板ID")
    report_config = Column(JSON, comment="报告配置")
    data_range_config = Column(JSON, comment="数据范围配置")
    
    # 执行信息
    is_active = Column(Boolean, default=True, comment="是否激活")
    execution_count = Column(Integer, default=0, comment="执行次数")
    success_count = Column(Integer, default=0, comment="成功次数")
    failed_count = Column(Integer, default=0, comment="失败次数")
    
    # 创建者
    creator_id = Column(Integer, ForeignKey('user.id'), comment="创建者ID")
    
    # 关系
    template = relationship("ReportTemplate")
    creator = relationship("User")
    
    def update_next_run_time(self):
        """更新下次运行时间"""
        # 这里可以根据schedule_type计算下次运行时间
        pass
    
    def increment_execution(self, success: bool = True):
        """增加执行统计"""
        self.execution_count += 1
        if success:
            self.success_count += 1
        else:
            self.failed_count += 1
        self.last_run_time = func.now()
    
    def to_dict(self) -> dict:
        """转换为字典"""
        result = super().to_dict()
        return result